package com.authine.cloudpivot.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.domain.Dto.SqDTO;
import com.authine.cloudpivot.domain.MessageParam;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.facade.WorkflowInstanceFacade;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.*;
import com.authine.cloudpivot.engine.domain.organization.Department;
import com.authine.cloudpivot.engine.enums.status.WorkflowInstanceStatus;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.open.OpenEngineFactory;
import com.authine.cloudpivot.engine.open.service.OpenEngine;
import com.authine.cloudpivot.engine.service.impl.runtime.BizAttachmentServiceImpl;
import com.authine.cloudpivot.engine.service.organization.DepartmentService;
import com.authine.cloudpivot.enums.AlarmTypeCodeEnum;
import com.authine.cloudpivot.enums.RxEnum;
import com.authine.cloudpivot.foundation.orm.api.dml.BizObjectRepository;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.service.CjfxOpenApiService2;
import com.authine.cloudpivot.util.CoordtransformUtils;
import com.authine.cloudpivot.util.EncryptionUtil;
import com.authine.cloudpivot.util.PolygonUtil;
import com.authine.cloudpivot.util.Result;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.controller.common.OSSController;
import com.authine.cloudpivot.web.api.controller.runtime.WorkflowInstanceRuntimeController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.runtime.WorkItemApprovalVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Base64;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.List;

/**
 * 前置机服务
 */
@RestController
    @RequestMapping("/api/front")
@Slf4j
public class FrontEndMachineController extends BaseController {

    private static final String USERID = "6b42ebe5236d4ecd84332710e5285fd0";

    private static final String DEPID = "ff8080819431dab7019444d8f9e10f01";

    @Autowired
    OSSController oSSController;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    BizObjectRepository bizObjectRepository;

    @Autowired
    BizObjectFacade bizObjectFacade;


    @Autowired
    BizAttachmentServiceImpl bizAttachmentService;

    @Autowired
    private OrganizationFacade organizationFacade;

    @Autowired
    private CjfxOpenApiService2 cjfxOpenApiService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private QueryReportSqlController queryReportSqlController;
    @Autowired
    private WorkflowInstanceFacade workflowInstanceFacade;
    @Autowired
    private JPANativeQuery jpaNativeQuery;




    /**
     * 应用：吹哨报到系统 模型：吹哨报到
     */
//    private static final String SCHMEA_CODE = "chuishao_001";  //prod
//    private static final String SCHMEA_CODE = "chuishao_001_test";  //test
    private static final String SCHMEA_CODE = "AlarmData";  //test
    /**
     * 应用：基础数据，模型：经纬度
     */
    private static final String JWDSJ = "jwdsj";

    private static final String WORKFLOW_CODE = "ce_001"; //prod
//    private static final String WORKFLOW_CODE = "ce_001_test"; //test

    private static final String ORIGINATOR_USERNAME = "ljy";

    @GetMapping("/test")
    public void test(@RequestParam("id") String id){
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("AlarmData", id);
        bizObject.put("ddddddd","满意");
//        bizObjectFacade.saveBizObject(bizObject.getCreater().getId(),bizObject,true);
//        String workflowInstanceId = bizObject.getWorkflowInstanceId();
//        List<WorkItemModel> workItems = workflowInstanceFacade.getWorkItems(workflowInstanceId, false);
//        workflowInstanceFacade.submitWorkItem(workItems.get(0).getParticipant(),workItems.get(0).getId(),true);
    }

    /**
     * 存储前置机信息
     */
    @PostMapping("/saveMachine")
    public Result saveMachineInfo(@RequestBody Map<String, Object> map) {
        if (MapUtil.isEmpty(map)) {
            return Result.fail();
        }
        try {
            String param = EncryptionUtil.decrypt((String) map.get("param"));
            List<Map<String, Object>> cloudParam = JSON.parseObject(param, List.class);
            String baseDataStr = EncryptionUtil.decrypt((String) map.get("baseData"));
            MessageParam baseData = JSON.parseObject(baseDataStr, MessageParam.class);
            String recordId = baseData.getRecordId();
            String queryRecoredId =String.format("SELECT * FROM `ikhmj_alarmdata` where record_id = '%s'",recordId);
            List list = jpaNativeQuery.getList(queryRecoredId, null, null);
            if (CollectionUtils.isNotEmpty(list)&&list.size()>0){
                return Result.ok();
            }
            // 查询流程发起人
            UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
            try {
                log.info("baseData数据信息:{}",JSON.toJSONString(baseData));
                log.info("cloudParam数据信息:{}",JSON.toJSONString(cloudParam));
                BizObjectModel bizObjectModel = makeUpData(baseData,cloudParam);
                String userId = bizObjectModel.getString(DefaultPropertyType.CREATER.getCode());
                String deptId = bizObjectModel.getString(DefaultPropertyType.CREATED_DEPT_ID.getCode());
                if (StringUtils.isBlank(userId) || StringUtils.isBlank(deptId)) {
//                    userId = originator.getId();
//                    deptId = originator.getDepartmentId();
                    userId = USERID;
                    deptId = DEPID;
                }
                bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
                bizObjectModel.setSequenceNo(baseData.getRecordId());
                bizObjectFacade.saveBizObjectModel(userId,bizObjectModel,null);
                LocalTime now = LocalTime.now();
                LocalTime start = LocalTime.of(9, 0); // 9:00:00
                LocalTime end = LocalTime.of(17, 0);  // 17:00:00
                boolean isBetween = !now.isBefore(start) && now.isBefore(end);
                log.info("当前时间是否在自动发起时间内:{}",isBetween);
                String jdId =(String) bizObjectModel.get("belong_street");
                if (isBetween && "2c9a8e6488ebff8b0188f03312ab02e0".equals(jdId)){
                    BizObjectModel alarmBizobojectModel= frontToCsData(bizObjectModel);
                    String sxt =baseData.getChannelCode();
                    String processSql= String.format("select * from ikhmj_chuishao_001 where sxtcode = '%s' and sequenceStatus = 'PROCESSING' and  IFNULL(eventStatus, '') <> '删除'",sxt);
                    List list1 = jpaNativeQuery.getList(processSql, null, null);
                    if (CollectionUtils.isEmpty(list1)){
                        workflowInstanceFacade.startWorkflowInstance(deptId, userId, null, WORKFLOW_CODE, alarmBizobojectModel, null, null, null, Boolean.TRUE);
                    }
                }
            } catch (Exception e) {
                log.error("sync Alarm data error,,msg:{}", e);
            }
            //处理图片

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return Result.ok();
    }

    public BizObjectModel frontToCsData(BizObjectModel objectModel){
        Map<String, Object> biz = objectModel.getData();
        Map<String, Object> data = new HashMap<>();
        data.put("source","告警");
        data.put("Radio1686744013849","网格长");
        data.put("Radio1698973951943","否");
        data.put("DeptSingle1698920071463",biz.get("belong_street"));
        data.put("ssjd","望麓园街道");
        data.put("DeptSingle1698920069239",biz.get("belong_community"));
        data.put("DeptSingle1698920067265",biz.get("belong_grid"));
        data.put("Address1685712261662",biz.get("event_address"));
        data.put("Dropdown1685712329221",biz.get("eventtheme"));
        data.put("Dropdown1685712342343",biz.get("oneclass"));
        data.put("ejfl",biz.get("twoclass"));
        data.put("sjfl",biz.get("threeclass"));
        data.put("Attachment1685712553506",biz.get("event_image"));
        data.put("sxtcode",biz.get("channelCode"));
        BizObjectModel bizObjectModel = new BizObjectModel("chuishao_001", data, Boolean.FALSE);
        bizObjectModel.setCreatedTime(new Date());
        bizObjectModel.setModifiedTime(new Date());
        return bizObjectModel;
    }

    public BizObjectModel creeateCsData(BizObjectModel objectModel){
        Map<String, Object> biz = objectModel.getData();
        Map<String, Object> data = new HashMap<>();
        data.put("source","告警");
        data.put("Radio1686744013849","网格长");
        data.put("Radio1698973951943","否");
        List<SelectionValue> jd =(List<SelectionValue>) biz.get("belong_street");
        data.put("DeptSingle1698920071463",jd.get(0).getId());
        data.put("ssjd",jd.get(0).getName());
        List<SelectionValue> sq =(List<SelectionValue>) biz.get("belong_community");
        if (CollectionUtils.isNotEmpty(sq)){
            data.put("DeptSingle1698920069239",sq.get(0).getId());
        }
        List<SelectionValue> wg =(List<SelectionValue>) biz.get("belong_grid");
        if (CollectionUtils.isNotEmpty(wg)){
            data.put("DeptSingle1698920067265",wg.get(0).getId());
        }
        data.put("Address1685712261662",biz.get("event_address"));
        data.put("Dropdown1685712329221",biz.get("eventtheme"));
        data.put("Dropdown1685712342343",biz.get("oneclass"));
        data.put("ejfl",biz.get("twoclass"));
        data.put("sjfl",biz.get("threeclass"));
        data.put("Attachment1685712553506",biz.get("event_image"));
        data.put("sxtcode",biz.get("channelCode"));
        BizObjectModel bizObjectModel = new BizObjectModel("chuishao_001", data, Boolean.FALSE);
        bizObjectModel.setCreatedTime(new Date());
        bizObjectModel.setModifiedTime(new Date());
        return bizObjectModel;
    }



    private BizObjectModel makeUpData(MessageParam messageParam,List<Map<String, Object>> cloudParam) {
        log.info("告警信息:{}",JSON.toJSONString(messageParam));
        Map<String, Object> data = new HashMap<>();
        data.put("record_id",messageParam.getRecordId());
        data.put("departmentName",messageParam.getDepartmentName());
        data.put("alarmTypeCode",messageParam.getAlarmTypeCode());
        data.put("address",messageParam.getAddress());
        data.put("districtCode",messageParam.getDistrictCode());
        data.put("districtName",messageParam.getDistrictName());
        data.put("dataType",messageParam.getDataType());
        data.put("departmentCode",messageParam.getDepartmentCode());
        data.put("longitude",messageParam.getLongitude());
        data.put("latitude",messageParam.getLatitude());
        data.put("alarmTypeName",messageParam.getAlarmTypeName());
        data.put("userName",messageParam.getUserName());
        data.put("userCode",messageParam.getUserCode());
        data.put("occurrenceTime", DateUtil.date(messageParam.getOccurrenceTime()));
        data.put("channelSn",messageParam.getChannelSn());
        data.put("channelCode",messageParam.getChannelCode());
        data.put("channelName",messageParam.getChannelName());
        putType(data,messageParam.getAlarmTypeCode());
        String departmentName = null;
        String longitude = messageParam.getLongitude();
        String latitudes = messageParam.getLatitude();
        String location = longitude + "," + latitudes;
        JSONObject convert = cjfxOpenApiService.convert(location);
        JSONObject address = cjfxOpenApiService.getAddress(convert.getStr("locations"));
        JSONObject regeocode = address.getJSONObject("regeocode");
        String formattedAddress = regeocode.getStr("formatted_address");
        // 填充地址信息
        departmentName = putAddress(data, longitude, latitudes, regeocode, formattedAddress);
        String jdDeptId;
        //填充街道信息
        jdDeptId = putJd(data, departmentName);
        String sqDeptId = null;
        // 填充社区信息
        sqDeptId = putSq(data, longitude, latitudes, jdDeptId, sqDeptId);
        String wgDeptId = null;
        // 填充网格信息
        wgDeptId = putWg(data, longitude, latitudes, sqDeptId, wgDeptId);
        if (StringUtils.isBlank(sqDeptId)&&StringUtils.isBlank(wgDeptId)) {
            String channelCode =messageParam.getChannelCode();
            String querycamara =String.format("SELECT * FROM `ilrv7_camerainformat` where channel_code = '%s' and belong_jd is not null limit 1",channelCode);
            List<Map<String,Object>> list1 = jpaNativeQuery.getList(querycamara, null, null);
            if (CollectionUtils.isNotEmpty(list1)){
                sqDeptId =(String) list1.get(0).get("belong_sq");
                wgDeptId =(String) list1.get(0).get("belong_wg");
                data.put("belong_community", sqDeptId);
                data.put("belong_grid", wgDeptId);
            }
        }
        // 填充创建人信息
        if (StringUtils.isNotBlank(wgDeptId)) {
            List<UserModel> usersByDeptId = organizationFacade.getUsersByDeptId(wgDeptId);
            if (CollectionUtils.isNotEmpty(usersByDeptId) && Objects.nonNull(usersByDeptId.get(0))) {
                data.put(DefaultPropertyType.CREATER.getCode(), usersByDeptId.get(0).getId());
                data.put(DefaultPropertyType.CREATED_DEPT_ID.getCode(), usersByDeptId.get(0).getDepartmentId());
            }
        }
        // 事件图片
        putImages(data, cloudParam);
        return new BizObjectModel(SCHMEA_CODE, data, Boolean.FALSE);

    }

    private  void putType(Map<String, Object> data,String alarmTypeCode){
        String query = String.format("SELECT eventtheme,oneclass,twoclass,threeclass FROM `ilrv7_alarmtype` where alarmTypeCode = '%s' limit 1",alarmTypeCode);
        List<Map<String,Object>> list = jpaNativeQuery.getList(query, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            data.put("eventtheme",list.get(0).get("eventtheme"));
            data.put("oneclass",list.get(0).get("oneclass"));
            data.put("twoclass",list.get(0).get("twoclass"));
            data.put("threeclass",list.get(0).get("threeclass"));
        }
    }

    private String putAddress(Map<String, Object> data, String longitude, String latitudes, JSONObject regeocode, String formattedAddress) {
        String departmentName = null;
        if (!MapUtils.isEmpty(regeocode)) {
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
            if (!MapUtils.isEmpty(addressComponent)) {
                departmentName = addressComponent.getStr("township");
                // 组装地址控件数据
                String province = addressComponent.getStr("province");
                String city = addressComponent.getStr("city");
                String district = addressComponent.getStr("district");
                String residueAddress = formattedAddress.replace(province, "").replace(city, "").replace(district, "");
                Map<String, Object> map = new HashMap<>();
                map.put("provinceName", province);
                map.put("cityName", city);
                map.put("districtName", district);
                map.put("address", residueAddress);
                map.put("lng", longitude);
                map.put("lat", latitudes);
                // 事件发生地址
                data.put("event_address", JSONUtil.toJsonStr(map));
            }
        }
        return departmentName;
    }

    private String putJd(Map<String, Object> data, String departmentName) {
        String departmentId = null;
        if (StringUtils.isNotBlank(departmentName)) {
            List<Department> departments = departmentService.getDepartmentsByName(departmentName, Boolean.FALSE);
            if (CollectionUtils.isNotEmpty(departments)) {
                departmentId = departments.get(0).getId();
                String deptName = departments.get(0).getName();
                // 所属街道（部门控件）
                data.put("belong_street", departmentId);
            }
        }
        return departmentId;
    }

    private String putWg(Map<String, Object> data, String longitude, String latitudes, String sqDeptId, String wgDeptId) {
        if (StringUtils.isNotBlank(sqDeptId)) {
            List<Map<String, Object>> wgJwd = queryReportSqlController.getJdJwd(sqDeptId);
//            double[] doublesWGS = CoordtransformUtils.GCJ02toWGS84(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
            for (Map<String, Object> map : wgJwd) {
                String jwd = MapUtils.getString(map, "jwd");
                if (StringUtils.isBlank(jwd)) {
                    continue;
                }
                List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                if (inPolygon) {
                    // 网格部门id
                    wgDeptId = MapUtils.getString(map, "id");
                    data.put("belong_grid", wgDeptId);
                    break;
                }
            }
        }
        return wgDeptId;
    }

    private String putSq(Map<String, Object> data, String longitude, String latitudes, String jdDeptId, String sqDeptId) {
        if (StringUtils.isNotBlank(jdDeptId)) {
            List<Map<String, Object>> sqJwd = queryReportSqlController.getJdJwd(jdDeptId);
//            double[] doublesWGS = CoordtransformUtils.GCJ02toWGS84(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            double[] doublesME = CoordtransformUtils.WGS84toMercator(Double.parseDouble(longitude), Double.parseDouble(latitudes));
            Point2D.Double aDouble = new Point2D.Double(doublesME[0], doublesME[1]);
            for (Map<String, Object> map : sqJwd) {
                String jwd = MapUtils.getString(map, "jwd");
                if (StringUtils.isBlank(jwd)) {
                    continue;
                }
                List<Point2D.Double> doubles = PolygonUtil.parsePointDoubles(jwd);
                boolean inPolygon = PolygonUtil.isInPolygon(aDouble, doubles);
                if (inPolygon) {
                    // 社区部门id
                    sqDeptId = MapUtils.getString(map, "id");
                    data.put("belong_community", sqDeptId);
                    break;
                }
            }
        }
        return sqDeptId;
    }

    private void putImages(Map<String, Object> data, List<Map<String, Object>> cloudParam) {
        if (CollectionUtils.isNotEmpty(cloudParam)) {
            List<Map<String, Object>> attachmentModels = new ArrayList<>();
            List<Map<String,Object>> rect = new ArrayList<>();
            for (Map<String, Object> pic : cloudParam) {
                // 解码Base64字符串
                try {
                    byte[] imageBytes = Base64.getDecoder().decode((String) pic.get("pic"));
                    UUID uuid = UUID.randomUUID();
                    String fileName = uuid + ".jpg";
                    MultipartFile file = new MockMultipartFile(fileName, fileName, "jpg", imageBytes);
                    InputStream inputStream = file.getInputStream();
                    List<Map<String,Object>> o =(List<Map<String, Object>>) pic.get("objectRect");
                    log.info("开始处理图片加框:",JSON.toJSONString(o));
                    if(CollectionUtils.isNotEmpty(o)){
                        for(Map<String,Object> m:o){
                            Integer objBottom =(Integer) m.get("objBottom");
                            Integer objLeft =(Integer) m.get("objLeft");
                            Integer objRight =(Integer) m.get("objRight");
                            Integer objTop =(Integer) m.get("objTop");
                            InputStream takephoto = takephoto(inputStream, objBottom, objLeft, objRight, objTop);
                            if (Objects.nonNull(takephoto)){
                                inputStream = takephoto;
                                log.info("处理图片完成");
                            }
                        }
                    }



                    OpenEngine openEngine = OpenEngineFactory.getOpenEngine();
                    String refId = openEngine.uploadFile(fileName, inputStream);
                    AttachmentModel attachmentModel = new AttachmentModel();
//                attachmentModel.setFileSize((file.getSize()));
                    attachmentModel.setRefId(refId);
                    attachmentModel.setName(refId);
                    attachmentModel.setSchemaCode(SCHMEA_CODE);
                    attachmentModel.setFileExtension(".jpg");
                    attachmentModel.setMimeType("image/jpg");
                    attachmentModels.add(BeanUtil.beanToMap(attachmentModel));

                    log.info("objectRectParam:{}",JSON.toJSONString(o));
                    Map<String,Object> map = new HashMap<>();
                    map.put(refId,JSON.toJSONString(o));
                    rect.add(map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (CollectionUtils.isNotEmpty(attachmentModels)) {
                data.put("event_image", attachmentModels);
                data.put("picobj",rect);

            }
        }
    }

    private InputStream takephoto(InputStream input,Integer objBottom,Integer objLeft,Integer objRight,Integer objTop){
        try {
            BufferedImage image = ImageIO.read(input);

            // 获取Graphics2D对象用于绘图
            Graphics2D g2d = image.createGraphics();

            // 设置画笔颜色和粗细
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(6)); // 边框宽度

            // 假设这是从接口获取的原始标注框坐标和图片尺寸
            int originalWidth = 8192;
            int originalHeight = 8192;
            int imgWidth = 1920; // Java环境中canvas的宽度（即BufferedImage的宽度）
            int imgHeight = 1080; // Java环境中canvas的高度（即BufferedImage的高度）



// 换算坐标
            double widthCoefficient = (double) imgWidth / originalWidth;
            double heightCoefficient = (double) imgHeight / originalHeight;

            int scaledLeft = (int) (objLeft * widthCoefficient);
            int scaledTop = (int) (objTop * heightCoefficient);
            int scaledRight = (int) (objRight * widthCoefficient);
            int scaledBottom = (int) (objBottom * heightCoefficient);

            // 绘制矩形
            g2d.drawRect(scaledLeft, scaledTop, scaledRight - scaledLeft, scaledBottom - scaledTop);

            // 释放资源
            g2d.dispose();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            InputStream modifiedImageStream = new ByteArrayInputStream(outputStream.toByteArray());
            return modifiedImageStream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/savecase")
    public Result savers(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"casedown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    public BizObjectModel makersDate(Map<String,Object> data,String USERID,String DEPID,String code){
        if ("caseitem".equals(code)){
            data.put("PARENTIDd",data.get("PARENTID"));
        }
        data.put(DefaultPropertyType.CREATER.getCode(), USERID);
        data.put(DefaultPropertyType.CREATED_DEPT_ID.getCode(), DEPID);
        return new BizObjectModel(code, data, Boolean.FALSE);
    }
    @PostMapping("/savehand")
    public Result savehand(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"handledown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/saveitem")
    public Result saveitem(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"caseitem");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/savedelaydown")
    public Result savedelaydown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"delaydown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/saveinfodown")
    public Result saveinfodown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"infodown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/savenotcontactdown")
    public Result savenotcontactdown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"notcontactdown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/savereturndown")
    public Result savereturndown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"returndown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/savesigndown")
    public Result savesigndown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"signdown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }
    @PostMapping("/savesupplementdown")
    public Result savesupplementdown(@RequestBody List<Map<String,Object>> list){
//        UserModel originator = organizationFacade.getUserByUsername(ORIGINATOR_USERNAME);
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makersDate(map, USERID,DEPID,"supplementdown");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }

    @GetMapping("/getMaxTime")
    public Result getMaxTime(@RequestParam(value = "type") String type){
        String tableName = RxEnum.getValueByName(type);
        String sql = String.format("select Max(CREATETIME) as CREATETIME from %s",tableName);
        List<Map<String,String>> list = jpaNativeQuery.getList(sql,null,null);
        String o = list.get(0).get("CREATETIME");
        return Result.ok(o);

    }

    @GetMapping("/delrx")
    @Transactional
    public Result delData(@RequestParam(value = "type") String type){
        String tableName = RxEnum.getValueByName(type);
        String timesql = String.format("select Max(CREATETIME) as CREATETIME from %s",tableName);
        List<Map<String,String>> list1 = jpaNativeQuery.getList(timesql,null,null);
        String o = list1.get(0).get("CREATETIME");
        String delSql = String.format("delete from %s where createtime > '%s'",tableName,o);
        Query nativeQuery = entityManager.createNativeQuery(delSql);
        nativeQuery.executeUpdate();
        return Result.ok();
    }

    @GetMapping("/gettotal")
    public Result getTotal(@RequestParam(value = "type") String type){
        String tableName = RxEnum.getValueByName(type);
        String timesql = String.format("select Max(CREATETIME) as CREATETIME from %s",tableName);
        List<Map<String,String>> list1 = jpaNativeQuery.getList(timesql,null,null);
        String o = list1.get(0).get("CREATETIME");
        String sql = String .format("select count(*) as total from %s where CREATETIME >= '%s'",tableName,o);
        List<Map<String, BigInteger>> list = jpaNativeQuery.getList(sql,null,null);
        BigInteger total = list.get(0).get("total");
        return Result.ok(total);
    }

    @PostMapping("/getcs")
    public Result getcs(@RequestBody Map<String,Object> map){
        String sql = String.format("SELECT * FROM `ikhmj_chuishao_001` where sequenceNo != 'DRAFT' limit %s,%s",map.get("page"),map.get("size"));
        System.out.println(sql);
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        return Result.ok(list);
    }
    @PostMapping("/getStreetNameByAddress")
    public  Result getStreetNameByAddress (String address){
        log.info("CjfxController:getStreetNameByAddress:address", address);
        JSONObject result = cjfxOpenApiService.geo(address);
        if (result.containsKey("geocodes")){
            JSONArray o =(JSONArray) result.get("geocodes");
            if (!Objects.isNull(o)){
                JSONObject gdAddress =(JSONObject) o.get(0);
                String location = gdAddress.getStr("location");
                String[] split = location.split(",");
                String longitude = split[0];
                String latitudes = split[1];
                String location2 = longitude + "," + latitudes;
                JSONObject address2 = cjfxOpenApiService.getAddress(location2);
                JSONObject regeocode = address2.getJSONObject("regeocode");
                String formattedAddress = regeocode.getStr("formatted_address");
                String departmentName=null;
                departmentName = putAddress(new HashMap<>(), longitude, latitudes, regeocode, formattedAddress);
                return Result.ok(departmentName);
            }

        }
    return null ;
    }

    @PostMapping("/saveData")
    public Result saveData(@RequestBody List<Map<String,Object>> list){
        for (Map<String,Object> map:list){
            BizObjectModel bizObjectModel = makeDate(map, USERID,DEPID,"data_12345");
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
        }
        return Result.ok();
    }

    /**
     * 集中诉求
     * @param data
     * @param USERID
     * @param DEPID
     * @param code
     * @return
     */
    @PostMapping("/saveJzsq")
    @Transactional
    public Result save(@RequestBody List<SqDTO> dtoList){
        for (SqDTO data:dtoList){
            Map<String,Object> map = new HashMap<>();
            map.put("concentrateDemandDate",data.getConcentrateDemandDate());
            map.put("concentrateDemandAddress",data.getConcentrateDemandAddress());
            map.put("totalDemand",data.getTotalDemand());
            map.put("questionTypeDistribution",data.getQuestionTypeDistribution());
            map.put("caseNumber",data.getCaseNumber());
            makeJzsq(data.getCaseNumber(),map);
            map.put(DefaultPropertyType.CREATER.getCode(), USERID);
            map.put(DefaultPropertyType.CREATED_DEPT_ID.getCode(), DEPID);
            BizObjectModel bizObjectModel = new BizObjectModel("concentrateDemand12345", map, Boolean.FALSE);
            bizObjectModel.setSequenceStatus(WorkflowInstanceStatus.COMPLETED.toString());
            bizObjectFacade.saveBizObjectModel(USERID,bizObjectModel,null);
            if(StringUtils.isNotBlank(bizObjectModel.getId())){
                String jzsqId = bizObjectModel.getId();
                String[] split = data.getCaseNumber().split(",");
                for(int i=0;i<split.length;i++){
                    String gdh = split[i];
                    String updateSql = String.format("update ic9na_data_12345 set jzsq = '%s'  where caseNumber ='%s'",jzsqId,gdh);
                    Query nativeQuery = entityManager.createNativeQuery(updateSql);
                    nativeQuery.executeUpdate();
                }
            }
        }
        return Result.ok();
    }

    public void makeJzsq(String caseNumber,Map<String,Object> data){
        String[] split = caseNumber.split(",");
        List<Map<String,Object>> gdlist = new ArrayList<>();
        String ssjd = null;
        for (int i=0;i<split.length;i++){
            String gdh = split[i];
            Map<String,Object> map = new HashMap<>();
            map.put("gdbh",gdh);
            String sql = String.format("select id,callContent,ssjd from ic9na_data_12345 where caseNumber = '%s' limit 1;",gdh);
            List<Map<String,String>> list = jpaNativeQuery.getList(sql, null, null);
            if(CollectionUtils.isNotEmpty(list)){
                String pdid = list.get(0).get("id");
                String ldnr =  list.get(0).get("callContent");
                ssjd = list.get(0).get("ssjd");
                map.put("caseNumber",pdid);
                map.put("callContent",ldnr);
            }
            gdlist.add(map);
        }
        data.put("ssjd",ssjd);
        data.put("caseNumberSubtable",gdlist);
    }

    public BizObjectModel makeDate(Map<String,Object> data,String USERID,String DEPID,String code){
        String ssjd =(String) data.get("ssjd");
        data.put(DefaultPropertyType.CREATER.getCode(), USERID);
        data.put(DefaultPropertyType.CREATED_DEPT_ID.getCode(), DEPID);
        return new BizObjectModel(code, data, Boolean.FALSE);
    }
    public String checkJd(String input){
        int streetIndex = input.indexOf("街道");
        if (streetIndex != -1) {
            // 找到"街道"的位置，并保留前面的部分 + "街道"
            return input.substring(0, streetIndex + 2); // +2 是因为"街道"是2个字符
        }
        return input; // 如果没有"街道"，返回原字符串
    }
}
